"""
该文件用于 对应各种文件的操作
"""

import os
import time
import re
import shutil
import json
from pathlib import Path
import constant
import xlrd
from utils.utils_json import modify_cfg
from constant import *
from utils.read_config import readconfig
from utils.utils_log import loggerCase


def get_project_value(file, key):
    """
    获得该工程的某些值,用于校验
    file:工程文件的位置
    key:读取某个值
    """
    with open(file, mode='r') as f:
        res = f.readlines()
        for i in res:
            if i.find(key) > 0:
                return re.findall('>(.+?)<', i)[0]
        else:
            raise Exception("该工程文件中的key不存在")


def get_desktop_path():
    """
    获得桌面路径
    :return: 获得桌面路径
    """
    return str(Path(os.path.expanduser("~")) / "Desktop")


def get_project_path():
    """
    :return: 返回指定结尾文件的路径
    """
    file_path = get_desktop_path() + "\\" + str(readconfig.project_new_project_name)
    file_p = ""
    for root, dirs, files in os.walk(file_path):
        for file in files:
            if file.endswith(readconfig.projectFileEndswith):
                file_p = os.path.join(root, file)
    return file_p


def create_folder(dir_list):
    """
    创建执行过程中所需要的文件夹
    dir_list：需要创建文件夹的list
    """
    for i in dir_list:
        if not os.path.exists(i):
            loggerCase.info(f"创建文件夹：{i}")
            os.mkdir(i)
        else:
            print(f'{i}文件已存在')


def cope_folder(source_path, target_path, is_cover=False):
    """
    复制文件
    :param source_path: 原文件地址
    :param target_path: 复制到哪个路径
    :param is_cover: 是否需要覆盖
    :return:
    """

    if is_cover:
        shutil.rmtree(target_path)
        shutil.copytree(source_path, target_path)
    else:
        if not os.path.exists(target_path):
            shutil.copytree(source_path, target_path)
        else:
            loggerCase.info(target_path + "已存在")


def copy_file(soure_file, target_file, is_cover=False):
    """
    复制文件
    :param soure_file: 原文件地址
    :param target_file: 复制到哪个路径
    :param is_cover: 是否需要覆盖
    :return:
    """
    if is_cover:
        shutil.copy(soure_file, target_file)
    else:
        if not os.path.exists(target_file):
            shutil.copy(soure_file, target_file)
        else:
            loggerCase.info(target_file + "已存在")


def move_file(source, target):
    """
    移动文件
    :param source: 原文件地址
    :param target: 复制到哪个路径
    :return:
    """
    if not os.path.exists(target):
        shutil.move(source, target)


def remove_file(path):
    """
    删除文件
    :param path: 文件路径
    :return:
    """
    try:
        shutil.rmtree(path=path)

        os.mkdir(path)
    except:
        pass


def read_excel_data(file, sheet, cell):
    """
    读取EXCEL的值
    :param file: 文件地址
    :param sheet: sheet
    :param cell: cell单元格
    :return:
    """
    book = xlrd.open_workbook(file)
    sheet = book.sheet_by_name(sheet)
    data = sheet.cell_value(cell[0], cell[1])
    return data

def create_default_dir():
    """
    创建默认目录
    :return:
    """
    default_dirs = [test_report_ui_path, ui_log_image_path]
    for dir in default_dirs:
        if not os.path.exists(dir):
            os.makedirs(dir)
def __judge_is_in_list(path, all_specified_folder_list):
    if path in all_specified_folder_list:
        return True
    return False

def delete_all_except_specified_folder(folder_path, specified_folder_list):
    """
    删除除了指导目录外的其他目录
    """
    all_specified_folder_list = set()
    for specified_folder in specified_folder_list:
        if not os.path.exists(specified_folder):
            break
        path = specified_folder
        all_specified_folder_list.add(path)
        # 添加上层目录直到工程根目录
        while path != folder_path:
            path = os.path.dirname(path)
            all_specified_folder_list.add(path)
        # 添加目录下的所有文件
        if os.path.isdir(specified_folder):
            for root, dirs, files in os.walk(specified_folder):
                for name in files:
                    file_path = os.path.join(root, name)
                    all_specified_folder_list.add(file_path)
                for name in dirs:
                    dir_path = os.path.join(root, name)
                    all_specified_folder_list.add(dir_path)

    for root, dirs, files in os.walk(folder_path, topdown=False):
        for name in files:
            file_path = os.path.join(root, name)
            if not __judge_is_in_list(file_path, all_specified_folder_list):
                os.remove(file_path)
                print(f"Deleted file: {file_path}")
        for name in dirs:
            dir_path = os.path.join(root, name)
            if not __judge_is_in_list(dir_path, all_specified_folder_list):
                shutil.rmtree(dir_path)
                print(f"Deleted folder: {dir_path}", root, name)


def read_operate(file_name):
    """
    关键词驱动读取用例操作
    :param file_name: [文件名]
    :return:
    """
    files = list(map(lambda x: test_data_path + os.sep + x, file_name))
    res = []
    for file in files:
        with open(file, 'r', encoding="utf-8") as file:
            cont = []
            flag = True
            # 获取第一个不为#的内容，获取循环次数和遇到问题是否继续
            while flag:
                first_data = file.readline()
                if not first_data.startswith("#"):
                    content = first_data.split(";")
                    number = int(content[0].split(":")[1])
                    is_exit = eval(content[1].split(":")[1])
                    flag = False
            # 获取剩下的内容
            data = file.readlines()
            get_data = []
            for i in data:
                if not i.startswith('#'):
                    i = i.rstrip()
                    get_data.append(i)
            cont.append(number)
            cont.append(is_exit)
            cont.append(get_data)
            cont.append(file.name)
            res.append(cont)
    return res